package com.apexedu.portal.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.apexedu.framework.util.ConfigUtil;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.framework.util.SysPropertiesUtil;
import com.apexedu.identity.IdConstants;
import com.apexedu.identity.entity.TSysMenu;
import com.apexedu.identity.entity.TSysUser;
import com.apexedu.portal.constant.ActionConstant;
import com.apexedu.portal.constant.Constants;
import com.apexedu.portal.entity.Lbxx;
import com.apexedu.portal.entity.TLbxx;
import com.apexedu.portal.util.DBMUtil;
import com.apexedu.portal.util.LittleTimer;
import com.apexedu.util.StringUtil;

import cn.com.sr.sdk.ext.api.mail.exmail.ExMailUtil;

/**
 * 门户4.0展示界面 上海工业技术学校
 * Created by ly on 2015/4/17.
 */
@Controller
public class MhShsgyjsxxController extends BaseController {

	/**
	 * 初始界面
	 *
	 * @return 初始界面
	 */
	@RequestMapping(value = ActionConstant.MhShgy.RequestMapping_init, method = RequestMethod.GET)
	public String init(HttpServletRequest request) {
		debug("<<{}>> init start", this.getClass().getSimpleName());
		LittleTimer timer = new LittleTimer();
		try {
			String type = getUsertype(request); //获取用户类型
			//initMsg(request, type);
			initDyfw(request, type); //初始化订阅服务
			//暂时为了避免报错，先注释掉
			initTzgg(request, type); //初始化通知公告
			initDate(request); //设置消息提醒模块中的周次 日期等

			Object zc = null;
			try {
				zc = new DBMUtil("jw").queryFieldValue("select xh from T_JX_Weeks where ID =dbo.fn_CM_getCurrentWeek()");
			} catch (Exception e) {
				e.printStackTrace();
			}
			request.setAttribute("zc", String.valueOf(zc));

			/* 获取腾讯企业邮箱相关信息 */
			TSysUser user = (TSysUser) request.getSession().getAttribute(IdConstants.SESSION_USER);
			String userId = user.getUserloginid();
			//接口令牌
			String access_token = ExMailUtil.getAccessToken();
			//免登陆进入邮箱的连接
			String sslLoginUrl = ExMailUtil.getSsoLoginUrl(access_token, userId);
			request.setAttribute("sslLoginUrl", sslLoginUrl);
			//未读邮件数
			String unreadMailNumber = ExMailUtil.getUnreadMailNumber(access_token, userId);
			request.setAttribute("unreadMailNumber", unreadMailNumber);
			//邮箱信息
			//String unreadMailInfo = ExMailUtil.getUnreadMailInfo(user.getUserloginid());
			//request.setAttribute("unreadMailInfo", JSON.parse(unreadMailInfo));
		} catch (Exception e) {
			//error("<<{}>> init error : {}", this.getClass().getSimpleName(), e);
			error(e, "<<{}>> init error : {}", this.getClass().getSimpleName());
			e.printStackTrace();
			//throw new RuntimeException(e);
		} finally {
			debug("<<{}>> init end : {}", this.getClass().getSimpleName(), timer.end());
		}
		return ActionConstant.MhShgy.Forward_init;
	}

	/**
	 * 初始化消息提醒
	 *
	 * @param request ---
	 * @param type 用户类型 参考Constants.MhUserType
	 * @throws Exception
	 */
	private void initMsg(HttpServletRequest request, String type) throws Exception {
		TSysUser user = (TSysUser) request.getSession().getAttribute(IdConstants.SESSION_USER);
		TLbxx lbxx = DBUtil.queryBean("select * from t_lbxx where wid = ?", TLbxx.class, ConfigUtil.getString("mh.msg." + type));
		if (StringUtil.isNotBlank(lbxx.getDb()) && StringUtil.isNotBlank(lbxx.getSql())) {
			List<Lbxx> list = new DBMUtil(lbxx.getDb()).queryAllBeanList(lbxx.getSql().replaceAll("\\{userid\\}", "'" + user.getUserloginid() + "'"), Lbxx.class);
			request.setAttribute("msgs", list);
		}
	}

	/**
	 * 初始化服务资源
	 *
	 * @param request --
	 * @param type 用户类型 参考Constants.MhUserType
	 */
	private void initDyfw(HttpServletRequest request, String type) {
		TSysUser user = (TSysUser) request.getSession().getAttribute(IdConstants.SESSION_USER);
		String mrfwid = StringUtil.EMPTY; //默认服务id
		if (Constants.MhUserType.LS.equals(type)) { //教职工
			mrfwid = "server_WAR_nj612portlet_INSTANCE_PlyXZt1kjRmj";
		} else if (Constants.MhUserType.LD.equals(type)) { //校领导
			mrfwid = "server_WAR_nj612portlet_INSTANCE_pwlC4relWHq6";
		} else if (Constants.MhUserType.XS.equals(type)) { //学生
			mrfwid = "server_WAR_nj612portlet_INSTANCE_wC3EoZnqKWOE";
		}
		List<TSysMenu> servers = getDyfwList(user.getUserloginid(), mrfwid);
		List<TSysMenu> serversType = getDyfwTypeList();
		List<TSysMenu> serversTypeNew = new ArrayList<TSysMenu>();
		for (TSysMenu menuType : serversType) {
			for (TSysMenu menu : servers) {
				if (menu.getUpmenuid().equals(menuType.getMenuid())) {
					serversTypeNew.add(menuType);
					break;
				}
			}
		}
		request.setAttribute("servers", servers); //服务资源集合
		request.setAttribute("serversType", serversTypeNew); //服务资源类型集合
		request.setAttribute("mrfwid", mrfwid); //服务资源组件id

		//是否可订阅资源 后台授权
		request.setAttribute("iskdy", DBUtil.count("select count(*) from t_sys_user_role a inner join t_sys_user b on a.userid=b.userid" + " where b.userloginid=? and a.roleid=?", user.getUserloginid(), ConfigUtil.getString("mh.server.dy.id")) > 0);
	}

	/**
	 * 初始化通知公告
	 *
	 * @param request --
	 * @param type 用户类型
	 */
	private void initTzgg(HttpServletRequest request, String type) throws Exception {
		TSysUser user = (TSysUser) request.getSession().getAttribute(IdConstants.SESSION_USER);
		if (Constants.MhUserType.LS.equals(type)) { //教职工站点
			List<Lbxx> dbsy = new ArrayList<Lbxx>();

			String sql = "";
			//原版(njw oracle)
			sql = "select cur.entry_id as id," + "'http://portal.shgyjs.cn/CASServer/login?service=http%3A%2F%2Fwww.shgyjs.cn%3A8083%2FUIProcessor%3F"
					+ "Creator%3Dworkflow%26Table%3D'||wf.name||'%26WorkID%3D'||cur.entry_id||'%26StepID%3D'||cur.step_id||'%26PageOnly%3Dtrue' as depart,"
					+ "'【教务学工】'||case when wf.subject is null then aa.wf_describe else wf.subject end as title,wf.init_date as time" + " from os_wfentry wf " + "inner join os_currentstep cur on wf.id=cur.entry_id"
					+ " inner join tuser t on instr(','||cur.owner||',',','||t.id||',')>0" + " inner join tuser init_t on wf.initiator=init_t.id " + "inner join os_workflowdefs aa on aa.wf_name=wf.name" + " where t.userid= '" + user.getUserloginid()
					+ "' order by cur.start_date desc";

			//新版（jw sqlserver）
			sql = "";
			sql += " SELECT";
			sql += " 		cur.entry_id AS id,";
			sql += " 		'http://portal.shgyjs.cn/CASServer/login?service=http%3A%2F%2Fjw.shgyjs.cn%2FUIProcessor%3FCreator%3Dworkflow%26Table%3D' + wf.name + '%26WorkID%3D' + CONVERT (VARCHAR(10), cur.entry_id) + '%26StepID%3D' + CONVERT (VARCHAR(10), cur.step_id) + '%26PageOnly%3Dtrue' AS depart,";
			sql += " 		'【教务学工】' + CASE";
			sql += " 			WHEN wf.subject IS NULL THEN";
			sql += " 			aa.wf_describe";
			sql += " 			ELSE";
			sql += " 			wf.subject";
			sql += " 			END AS title,";
			sql += "  	wf.init_date AS TIME";
			sql += " FROM";
			sql += " 	os_wfentry wf";
			sql += " INNER JOIN os_currentstep cur ON wf.id = cur.entry_id";
			sql += " INNER JOIN tuser t ON charindex(";
			sql += " 	',' + CONVERT (VARCHAR(10), t.id) + ',',";
			sql += " 	',' + cur.owner + ','";
			sql += " ) > 0";
			sql += " INNER JOIN tuser init_t ON wf.initiator = init_t.id";
			sql += " INNER JOIN os_workflowdefs aa ON aa.wf_name = wf.name";
			sql += " WHERE";
			sql += " 	t.userid = '" + user.getUserloginid() + "'";
			sql += " ORDER BY";
			sql += " 	cur.start_date DESC";

			dbsy.addAll(getTzgg(new DBMUtil("jw"), null, sql));//教务学工

			dbsy.addAll(getTzgg(new DBMUtil("oa"), null,
					" select cur.entry_id as id," + "'http://portal.shgyjs.cn/CASServer/login?service=http%3A%2F%2Fportal.shgyjs.cn%3A8082%2FUIProcessor%3F"
							+ "Creator%3Dworkflow%26Table%3D'||wf.name||'%26WorkID%3D'||cur.entry_id||'%26StepID%253D'||cur.step_id||'%26PageOnly%3Dtrue' as depart,"
							+ "'【行政办公】'||case when wf.subject is null then aa.wf_describe else wf.subject end as title,wf.init_date as time" + " from os_wfentry wf inner join os_currentstep cur on wf.id=cur.entry_id"
							+ " inner join tuser t on instr(','||cur.owner||',',','||t.id||',')>0" + " inner join tuser init_t on wf.initiator=init_t.id inner join os_workflowdefs aa on aa.wf_name=wf.name" + " where t.userid= '" + user.getUserloginid()
							+ "' order by cur.start_date desc"));//行政办公
			dbsy.addAll(getTzgg(new DBMUtil("hq"), null,
					" select cur.entry_id as id," + "'http://portal.shgyjs.cn/CASServer/login?service=http%3A%2F%2Fportal.shgyjs.cn%3A8085%2FUIProcessor%3F"
							+ "Creator%3Dworkflow%26Table%3D'||wf.name||'%26WorkID%3D'||cur.entry_id||'%26StepID%3D'||cur.step_id||'%26PageOnly%3Dtrue' as depart,"
							+ "'【后勤资产】'||case when wf.subject is null then aa.wf_describe else wf.subject end as title,wf.init_date as time" + " from os_wfentry wf inner join os_currentstep cur on wf.id=cur.entry_id"
							+ " inner join tuser t on instr(','||cur.owner||',',','||t.id||',')>0" + " inner join tuser init_t on wf.initiator=init_t.id inner join os_workflowdefs aa on aa.wf_name=wf.name" + " where t.userid= '" + user.getUserloginid()
							+ "' order by cur.start_date desc"));//后勤资产
			dbsy.addAll(getTzgg(new DBMUtil("hr"), null,
					" select cur.entry_id as id," + "'http://portal.shgyjs.cn/CASServer/login?service=http%3A%2F%2Fportal.shgyjs.cn%3A8081%2FUIProcessor%3F"
							+ "Creator%3Dworkflow%26Table%3D'||wf.name||'%26WorkID%3D'||cur.entry_id||'%26StepID%3D'||cur.step_id||'%26PageOnly%3Dtrue' as depart,"
							+ "'【人力资源】'||case when wf.subject is null then aa.wf_describe else wf.subject end as title,wf.init_date as time" + " from os_wfentry wf inner join os_currentstep cur on wf.id=cur.entry_id"
							+ " inner join tuser t on instr(','||cur.owner||',',','||t.id||',')>0" + " inner join tuser init_t on wf.initiator=init_t.id inner join os_workflowdefs aa on aa.wf_name=wf.name" + " where t.userid= '" + user.getUserloginid()
							+ "' order by cur.start_date desc"));//人力资源
			Collections.sort(dbsy, new Comparator<Lbxx>() {
				@Override
				public int compare(Lbxx o1, Lbxx o2) {
					if (o2.getTime().getTime() - o1.getTime().getTime() >= 0) {
						return 1;
					} else {
						return -1;
					}
				}
			});
			request.setAttribute("dbts", dbsy.size());
			request.setAttribute("dbsy", dbsy); //待办事宜
			int dbsyys = dbsy.size() % 7 == 0 ? dbsy.size() / 7 : (dbsy.size() / 7 + 1);
			request.setAttribute("dbsyys", dbsyys == 0 ? 1 : dbsyys);//待办事宜页数
		} else if (Constants.MhUserType.LD.equals(type)) { //校领导站点
			List<Lbxx> dbsy = new ArrayList<Lbxx>();

			String sql = "";
			//原版(njw oracle)
			sql = "select cur.entry_id as id," + "'http://portal.shgyjs.cn/CASServer/login?service=http%3A%2F%2Fwww.shgyjs.cn%3A8083%2FUIProcessor%3F"
					+ "Creator%3Dworkflow%26Table%3D'||wf.name||'%26WorkID%3D'||cur.entry_id||'%26StepID%3D'||cur.step_id||'%26PageOnly%3Dtrue' as depart,"
					+ "'【教务学工】'||case when wf.subject is null then aa.wf_describe else wf.subject end as title,wf.init_date as time" + " from os_wfentry wf " + "inner join os_currentstep cur on wf.id=cur.entry_id"
					+ " inner join tuser t on instr(','||cur.owner||',',','||t.id||',')>0" + " inner join tuser init_t on wf.initiator=init_t.id " + "inner join os_workflowdefs aa on aa.wf_name=wf.name" + " where t.userid= '" + user.getUserloginid()
					+ "' order by cur.start_date desc";

			//新版（jw sqlserver）
			sql = "";
			sql += " SELECT";
			sql += " 		cur.entry_id AS id,";
			sql += " 		'http://portal.shgyjs.cn/CASServer/login?service=http%3A%2F%2Fjw.shgyjs.cn%2FUIProcessor%3FCreator%3Dworkflow%26Table%3D' + wf.name + '%26WorkID%3D' + CONVERT (VARCHAR(10), cur.entry_id) + '%26StepID%3D' + CONVERT (VARCHAR(10), cur.step_id) + '%26PageOnly%3Dtrue' AS depart,";
			sql += " 		'【教务学工】' + CASE";
			sql += " 			WHEN wf.subject IS NULL THEN";
			sql += " 			aa.wf_describe";
			sql += " 			ELSE";
			sql += " 			wf.subject";
			sql += " 			END AS title,";
			sql += "  	wf.init_date AS TIME";
			sql += " FROM";
			sql += " 	os_wfentry wf";
			sql += " INNER JOIN os_currentstep cur ON wf.id = cur.entry_id";
			sql += " INNER JOIN tuser t ON charindex(";
			sql += " 	',' + CONVERT (VARCHAR(10), t.id) + ',',";
			sql += " 	',' + cur.owner + ','";
			sql += " ) > 0";
			sql += " INNER JOIN tuser init_t ON wf.initiator = init_t.id";
			sql += " INNER JOIN os_workflowdefs aa ON aa.wf_name = wf.name";
			sql += " WHERE";
			sql += " 	t.userid = '" + user.getUserloginid() + "'";
			sql += " ORDER BY";
			sql += " 	cur.start_date DESC";

			dbsy.addAll(getTzgg(new DBMUtil("jw"), null, sql));//教务学工

			dbsy.addAll(getTzgg(new DBMUtil("oa"), null,
					" select cur.entry_id as id," + "'http://portal.shgyjs.cn/CASServer/login?service=http%3A%2F%2Fportal.shgyjs.cn%3A8082%2FUIProcessor%3F"
							+ "Creator%3Dworkflow%26Table%3D'||wf.name||'%26WorkID%3D'||cur.entry_id||'%26StepID%253D'||cur.step_id||'%26PageOnly%3Dtrue' as depart,"
							+ "'【行政办公】'||case when wf.subject is null then aa.wf_describe else wf.subject end as title,wf.init_date as time" + " from os_wfentry wf inner join os_currentstep cur on wf.id=cur.entry_id"
							+ " inner join tuser t on instr(','||cur.owner||',',','||t.id||',')>0" + " inner join tuser init_t on wf.initiator=init_t.id inner join os_workflowdefs aa on aa.wf_name=wf.name" + " where t.userid= '" + user.getUserloginid()
							+ "' order by cur.start_date desc"));//行政办公

			dbsy.addAll(getTzgg(new DBMUtil("hq"), null,
					" select cur.entry_id as id," + "'http://portal.shgyjs.cn/CASServer/login?service=http%3A%2F%2Fportal.shgyjs.cn%3A8085%2FUIProcessor%3F"
							+ "Creator%3Dworkflow%26Table%3D'||wf.name||'%26WorkID%3D'||cur.entry_id||'%26StepID%3D'||cur.step_id||'%26PageOnly%3Dtrue' as depart,"
							+ "'【后勤资产】'||case when wf.subject is null then aa.wf_describe else wf.subject end as title,wf.init_date as time" + " from os_wfentry wf inner join os_currentstep cur on wf.id=cur.entry_id"
							+ " inner join tuser t on instr(','||cur.owner||',',','||t.id||',')>0" + " inner join tuser init_t on wf.initiator=init_t.id inner join os_workflowdefs aa on aa.wf_name=wf.name" + " where t.userid= '" + user.getUserloginid()
							+ "' order by cur.start_date desc"));//后勤资产

			dbsy.addAll(getTzgg(new DBMUtil("hr"), null,
					" select cur.entry_id as id," + "'http://portal.shgyjs.cn/CASServer/login?service=http%3A%2F%2Fportal.shgyjs.cn%3A8081%2FUIProcessor%3F"
							+ "Creator%3Dworkflow%26Table%3D'||wf.name||'%26WorkID%3D'||cur.entry_id||'%26StepID%3D'||cur.step_id||'%26PageOnly%3Dtrue' as depart,"
							+ "'【人力资源】'||case when wf.subject is null then aa.wf_describe else wf.subject end as title,wf.init_date as time" + " from os_wfentry wf inner join os_currentstep cur on wf.id=cur.entry_id"
							+ " inner join tuser t on instr(','||cur.owner||',',','||t.id||',')>0" + " inner join tuser init_t on wf.initiator=init_t.id inner join os_workflowdefs aa on aa.wf_name=wf.name" + " where t.userid= '" + user.getUserloginid()
							+ "' order by cur.start_date desc"));//人力资源

			Collections.sort(dbsy, new Comparator<Lbxx>() {
				@Override
				public int compare(Lbxx o1, Lbxx o2) {
					if (o2.getTime().getTime() - o1.getTime().getTime() >= 0) {
						return 1;
					} else {
						return -1;
					}
				}
			});
			request.setAttribute("dbts", dbsy.size());
			request.setAttribute("dbsy", dbsy); //待办事宜
			int dbsyys = dbsy.size() % 7 == 0 ? dbsy.size() / 7 : (dbsy.size() / 7 + 1);
			request.setAttribute("dbsyys", dbsyys == 0 ? 1 : dbsyys);//待办事宜页数
		}
	}

	/**
	 * 服务订阅界面
	 *
	 * @param serverid 服务资源组件id
	 * @param request ---
	 * @return 服务订阅界面
	 */
	@RequestMapping(value = ActionConstant.MhShgy.RequestMapping_server, method = RequestMethod.GET)
	public String server(@PathVariable(ActionConstant.MhShgy.Variable_serverid) String serverid, HttpServletRequest request) {
		debug("<<{}>> server start", this.getClass().getSimpleName());
		TSysUser user = (TSysUser) request.getSession().getAttribute(IdConstants.SESSION_USER);
		LittleTimer timer = new LittleTimer();
		try {
			List<TSysMenu> listType = DBUtil.queryAllBeanList("select wid as menuid,name as menuname" + " from T_NAVIGATION t where t.portletid=? order by t.wid", TSysMenu.class, serverid);
			for (TSysMenu menuType : listType) {
				menuType.getChildMenu().addAll(getDyfwList(user.getUserloginid(), serverid + menuType.getMenuid()));
			}
			request.setAttribute("serverid", serverid);
			request.setAttribute("listType", listType);
			return ActionConstant.MhShgy.Forward_server;
		} catch (Exception e) {
			error("<<{}>> server error : {}", this.getClass().getSimpleName(), e);
			throw new RuntimeException(e);
		} finally {
			debug("<<{}>> server end : {}", this.getClass().getSimpleName(), timer.end());
		}
	}

	/**
	 * 流程代码业务导航界面
	 *
	 * @param request --
	 * @return workflowTypes
	 */
	@RequestMapping(value = ActionConstant.MhShgy.RequestMapping_workflow, method = RequestMethod.GET)
	public String workflow(HttpServletRequest request) {
		debug("<<{}>> workflow start", this.getClass().getSimpleName());
		TSysUser user = (TSysUser) request.getSession().getAttribute(IdConstants.SESSION_USER);
		LittleTimer timer = new LittleTimer();
		try {
			List<TLbxx> workflowTypes = DBUtil.queryAllBeanList("select * from t_lbxx t" + " where t.lx = '1' and t.upid = '1' and t.state='1' order by orderno", TLbxx.class);
			List<TLbxx> workflows = DBUtil
					.queryAllBeanList("select lb.wid,lb.upid,lb.name," + " '/s/uc/mh/f?q='||db.link||'/StartWorkflow?PageOnly=true%26Workflow='||lb.des as url from t_lbxx lb" + " inner join t_sys_role_workflow  rw on lb.wid=rw.workflowid"
							+ " inner join t_sys_user_role ur on ur.roleid= rw.roleid" + " inner join t_db db on db.code=lb.db" + " where lb.lx=1 and lb.upid!='1' and ur.userid=?" + " order by lb.upid,lb.orderno", TLbxx.class, user.getUserid());
			for (int i = 0; i < workflowTypes.size(); i++) {
				TLbxx workflowType = workflowTypes.get(i);
				for (TLbxx workflow : workflows) {
					if (workflow.getUpid().equals(workflowType.getWid())) {
						workflowType.getLbxxList().add(workflow);
					}
				}
				if (workflowType.getLbxxList().isEmpty()) {
					workflowTypes.remove(i);
					i--;
				}
			}
			request.setAttribute("workflowTypes", workflowTypes);
			return ActionConstant.MhShgy.Forward_workflow;
		} catch (Exception e) {
			error("<<{}>> workflow error : {}", this.getClass().getSimpleName(), e);
			throw new RuntimeException(e);
		} finally {
			debug("<<{}>> workflow end : {}", this.getClass().getSimpleName(), timer.end());
		}
	}

	/**
	 * 跳转到考试系统
	 *
	 * @param request ---
	 */
	@RequestMapping(value = ActionConstant.MhShgy.RequestMapping_test, method = RequestMethod.GET)
	public void test(HttpServletRequest request, HttpServletResponse response) {
		debug("<<{}>> test start", this.getClass().getSimpleName());
		TSysUser user = (TSysUser) request.getSession().getAttribute(IdConstants.SESSION_USER);
		LittleTimer timer = new LittleTimer();
		try {
			response.sendRedirect(SysPropertiesUtil.get("testUrl") + "&username=" + user.getUserloginid() + "&pwd=" + SysPropertiesUtil.get("testPwd"));
		} catch (Exception e) {
			error("<<{}>> test error : {}", this.getClass().getSimpleName(), e);
			throw new RuntimeException(e);
		} finally {
			debug("<<{}>> test end : {}", this.getClass().getSimpleName(), timer.end());
		}
	}
}